<?php

namespace Forum\ForumBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Forum\ForumBundle\Form\TopicForm;
use Forum\ForumBundle\Form\ReplyForm;

use Forum\ForumBundle\Entity\Topic;
use Forum\ForumBundle\Entity\Message;
use Forum\ForumBundle\Entity\CategorieTopic;



class DefaultController extends Controller
{
    /**
     *
     * @extra:Route("/create-topic/cat/{id}", name="_forum_create_topic")
     * @extra:Template()
     */
    public function create_topicAction($id)
    {
        $form = TopicForm::create($this->get('form.context'), 'create_topic');

        $form->bind($this->container->get('request'), $form);

        if($form->isValid()){

            $em = $this->get('doctrine.orm.entity_manager');

          

            $form->save($em);

        }

        return array('form' => $form);
    }

    /**
     *
     * @extra:Route("/reply/{id}/{topic_name}", name="_forum_reply")
     * @extra:Template()
     */
    public function reply_topicAction($id) //
    {

        $form = ReplyForm::create($this->get('form.context'), 'reply_topic');

        $form->bind($this->container->get('request'), $form);

        if($form->isValid()){

            $em = $this->get('doctrine.orm.entity_manager');

            $form->save($em, $id);

        }

        return array('reply_form' => $form);
    }


    /**
     *
     * @extra:Route("", name="_forum_home")
     * @extra:Template()
     */
    public function show_forumAction() // Page d'acceuil du forum
    {

        $em = $this->get('doctrine.orm.entity_manager');

        $query = $em->createQuery('SELECT c FROM Forum\ForumBundle\Entity\CategorieTopic c WHERE c.parent IS NULL');
        $categories = $query->getResult();

        foreach ($categories as $cat){
//            $query = $em->createQuery('SELECT c FROM Forum\ForumBundle\Entity\CategorieTopic c WHERE c.parent = ?1');
//            $query->setParameter(1, $cat->getId_categorie());
//            $sub_categories[] = $query->getResult();
        }

        return array("categories" => $categories,
                     "subCategories" => $sub_categories);
    }

    
    /**
     *
     * @extra:Route("/category/{id}/{cat_name}", name="_forum_list_cat"),
     * @extra:Template()
     */
    public function show_categorieAction($id) //liste des topics d'une catégorie ou liste des catégories
    {

        $em = $this->get('doctrine.orm.entity_manager');

        $categorie = $em->getRepository('Forum\ForumBundle\Entity\CategorieTopic')->findOneBy(array("id_categorie" => $id));
        $sous_categories = $categorie->getEnfants();

        if(count($sous_categories) > 0)
        {
            return array("categorie" => $categorie, "topic" => 0);
        }
        else
        {
            return array("categorie" => $categorie, "topic" => 1);
        }

    }


    /**
     * @extra:Routes({
     *  @extra:Route("/topic/{id}/{topic_name}", name="_forum_topic"),
     *  @extra:Route("/topic/{id}/{topic_name}/{page}", name="_forum_topic_page")
     * })
     * @extra:Template()
     */
    public function show_topicAction($id, $page = 1)
    {

        $em = $this->get('doctrine.orm.entity_manager');


        // On récupère l'objet du topic avec les messages
        $topic = $em->getRepository('Forum\ForumBundle\Entity\Topic')->findOneBy(array("id_topic"=>$id));

        // On incrémente le nombre de vues à chaque visite
        $topic->setVue($topic->getVue() + 1);


        // On récupère toutes les catégories et sous-catégories
        // correspondantes au topic
        $categorie = $topic->getCategorieTopic();

        $em->persist($topic);
        $em->flush();

        $categories[] = $categorie;

        while(gettype($categorie->getParent()) != 'NULL' ){

            $categorie = $em->getRepository('Forum\ForumBundle\Entity\CategorieTopic')->findOneBy(array("id_categorie"=>$categorie->getParent()->getId_categorie()));

            $categories[] = $categorie;

        }

        $categories = array_reverse($categories);



        // Données pour la paginations
        $nbMessages = count($topic->getMessages()); // nombre de messages du topic
        $messagesPerPage = 3; // Nombre de messages par page
        $delta = 3; // Nombre de pages à affichier avant et après la page actuelle

        $nbPages = ceil($nbMessages / $messagesPerPage);

        if($page > $nbPages)
            $currentPage = $nbPages;
        else
            $currentPage = $page;

        
        $titleForUrl = replaceSpecialChar($topic->getNom_topic());


        return array("topic" => $topic,
                     "titleForUrl" => $titleForUrl, // pour l'url
                     "route" => "_forum_topic", // pour la pagination
                     "nbPages" => $nbPages,
                     "nbElts" => $nbMessages,
                     "delta" => $delta,
                     "eltsPerPage" => $messagesPerPage,
                     "currentPage" => $currentPage,
                     "categories" => $categories);
    }

    

}

function validWord($str){

    //$minLength = 3;

    //if(preg_match("#[0-9]#", $str))
    //    return true;

    if(strlen($str) > 3)
        return true;
    return false;

}


function titleToUrl($title)
{
    // Supression des caractères spéciaux
    //$title = replaceSpecialchar($title);

    //on récupère chaque mot
    $words = explode(" ", $title);

    // Supprime les mots trop courts (<= 3) qui ne comportent pas de chiffre
    // $words = array_filter($words, "empty");

    $maxNbWords = 8;
    $nbWords = count($words);

    if($nbWords < $maxNbWords)
        $maxNbWord = $nbWords;

    $result = "";

    for($i = 0; $i < $maxNbWords; $i++){
        $result .= $words[$i]."-";
    }

    return substr($result, 0, -1);

}

function replaceSpecialChar($string) {

    //$search = array ('#[éèêëÊË]#i','#[àâäÂÄ]#i','#[îïÎÏ]#i','#[ûùüÛÜ]#i','#[ôöÔÖ]#i','#[ç]#i','#[^a-zA-Z0-9]#');
    //$replace = array ('e','a','i','u','o','c',' ');

    $search = array ('#[éèêëÊË]#i','#[àâäÂÄ]#i','#[îïÎÏ]#i','#[ûùüÛÜ]#i','#[ôöÔÖ]#i','#[ç]#i');
    $replace = array ('e','a','i','u','o','c');

    return strtolower(preg_replace($search, $replace, $string));
}



